package com.xykj.enterprise.wechat.wap.service;

import com.xykj.enterprise.wechat.base.web.domain.AjaxData;
import com.xykj.enterprise.wechat.base.web.domain.AjaxPage;
import com.ydn.appserver.Response;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Feng Chen
 */
@Slf4j
public abstract class BaseService {

    protected <T> AjaxData<T> convertData(Response response, Class<T> type) {
        AjaxData result = null;
        if (response.isSuccess()) {
            result = AjaxData.success(response.getObject("data", type));

        } else {
            log.error("错误code:{}, 错误信息{}", response.getCode(), response.getMessage());
            result = AjaxData.failure(response.getCode(), response.getMessage());
        }
        return result;
    }

    protected <T> AjaxPage<T> convertPage(Response response, Class<T> type) {
        AjaxPage result = null;
        if (response.isSuccess()) {
            Integer total = response.getInteger("total");
            if (total == null) {
                total = 0;
            }
            Integer count = response.getInteger("count");
            if (count == null) {
                count = 0;
            }
            result = AjaxPage.success(response.getList("list", type), total, count);
        } else {
            log.error("错误code:{}, 错误信息{}", response.getCode(), response.getMessage());
            result = AjaxPage.failure(response.getCode(), response.getMessage());
        }
        return result;
    }

    protected AjaxData convertData(Response response) {
        AjaxData result = null;
        if (response.isSuccess()) {
            result = AjaxData.success(response.getData().get("data"));
        } else {
            log.error("错误code:{}, 错误信息{}", response.getCode(), response.getMessage());
            result = AjaxData.failure(response.getCode(), response.getMessage());
        }
        return result;
    }
}
